package com.sky.module.system.heart.runnable;

import cn.hutool.core.net.NetUtil;
import com.aliyun.oss.common.utils.StringUtils;
import com.sky.module.system.heart.domain.entity.HeartEntity;
import com.sky.module.system.heart.handle.HeartBeatRecordHandler;
import com.sky.module.system.heart.manager.HeartBeatManager;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author
 * @date 2023/3/11 16:12
 **/
public class HeartRunnable implements Runnable {
    // 心跳状态信息持久化处理类
    private HeartBeatRecordHandler heartBeatRecordHandler;
    // 项目路径
    private String projectPath;

    // 服务ip 多网卡
    private List<String> serverIps;
    // 进程id
    private Integer processoId;

    // 进程开启时间
    private LocalDateTime processStartTime;

    public HeartRunnable(HeartBeatRecordHandler heartBeatRecordHandler) {
        this.heartBeatRecordHandler = heartBeatRecordHandler;
        this.init();
    }

    /***
     * @description 初始化一些心跳状态信息
     *
     * @return void
     * @date 2023/3/3 22:25
     *
     */
    private void init() {
//        TODO 这里进行心跳状态信息的初始化

        final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        final String name = runtimeMXBean.getName(); // 得到名字
        this.processoId = Integer.parseInt(  //   获取进程id
                name.split("@")[0]
        );
        // 项目路径
        this.projectPath = System.getProperty("user.dir");
        // 开始时间
        LocalDateTime processStartTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(runtimeMXBean.getStartTime()), ZoneId.systemDefault());
        this.processStartTime = processStartTime;
        this.serverIps = new ArrayList<>(NetUtil.localIpv4s());
    }

    /***
     * @description 心跳检测
     *
     * @return void
     * @date 2023/3/11 16:17
     *
     */
    // TODO  执行效率
    @Override
    public void run() {

        System.out.println(new Date().toLocaleString());
//            获取心跳状态的信息，然后调用状态持久化处理类
        HeartEntity heartBeatRecord = new HeartEntity();
//         测试
        heartBeatRecord.setProcessNo(this.processoId + "");
        heartBeatRecord.setProcessStartTime(this.processStartTime);
        heartBeatRecord.setProcessNo(processoId + "");
        // 心跳时间
        heartBeatRecord.setProjectPath(this.projectPath);
        heartBeatRecord.setHeartBeatTime(LocalDateTime.now());
        heartBeatRecord.setServerIp(StringUtils.join(":", this.serverIps)
        );
        // 心跳信息持久化 调用
        heartBeatRecordHandler.handler(heartBeatRecord);
    }
}
